import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class View extends JPanel 
	implements MouseListener, KeyListener, ComponentListener
{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    int width, height;
    Solver solver;

    public View ()
    {
        super();
        width = getSize().width;
        height = getSize().height;
        solver = null;
        addMouseListener(this);
        addKeyListener(this);
        addComponentListener(this);
    	setFocusable(true);
    }
   
    public void setSolver(Solver s)
    {
        solver = s;
    }
   
    Image buffer;
    public void paint(final Graphics g) {
        if (buffer == null) {
            buffer = createImage(width, height);
        }
        solver.paint(buffer.getGraphics(), width, height);
        g.drawImage(buffer, 0, 0, this);
    }

    public void componentMoved(ComponentEvent e) {}

    public void componentResized(ComponentEvent e) {
        int minwidth = 200;
        int minheight = 200;
        int newwidth = getSize().width;
        int newheight = getSize().height;
        boolean changed = false;
        if (newwidth < minwidth) {
            changed = true;
            width = minwidth;
        } else {
            width = newwidth;
        }
        if (newheight < minheight) {
            changed = true;
            height = minheight;
        } else {
            height = newheight;
        }
        if (changed) {
            setSize(width, height);
        }
        buffer = null;
        repaint();
    }
   
    public void componentShown(ComponentEvent e) {}

    public void componentHidden(ComponentEvent e) {}
    
    public void keyTyped(KeyEvent e) {
    	solver.updateHighlightedCell(e.getKeyChar());
    }

    public void keyPressed(KeyEvent e) {
    	solver.moveHighlight(e);
    }

    public void keyReleased(KeyEvent e) {}

    public void mousePressed(MouseEvent e) {
    	requestFocusInWindow();
    	solver.highlightClickedCell(e.getX(), e.getY(), width, height);
    }

    public void mouseReleased(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) { }
}
